<?php

namespace app\api\controller;

use app\admin\model\member\Member;
use app\api\model\BaseModel;
use app\api\model\GoodsModel;
use app\api\model\HomeOrderModel;
use app\api\model\MemberModel;
use app\api\model\RecycleOrderModel;
use app\api\model\RecyclePriceModel;
use app\api\model\UserModel;
use app\api\service\JsonService;
use app\common\controller\Api;
use think\Cache;
// use think\facade\Request;
use wx\WxMessage;
use think\Db;
use function Couchbase\defaultDecoder;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\IOFactory;
// use PhpOffice\PhpSpreadsheet\Spreadsheet;
// use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
// use PhpOffice\PhpSpreadsheet\Writer\Pdf\Tcpdf;
use TCPDF;
// 引入 TCPDF 类
// require_once(ROOT_PATH . 'vendor/tcpdf/tcpdf.php');

// 引入 TCPDF 类
// require_once(ROOT_PATH . 'vendor/tcpdf/tcpdf.php');
/**
 * 家政接口
 */
class Home extends Api
{
    protected $noNeedLogin = ['goodsDetail','getTableFields'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    //获取10条搜索条件
    public function getMemberSearhList()
    {
        return JsonService::successful(DB::table('hs_search_history')->where('user_id',$this->request->uid)->order('id', 'desc')
            ->limit(10)
            ->select());
    }
    //获取客户列表 
    public function getMemberList()
    {
        $params = $this->request->param();
        if (empty($params['type'])) {
            return JsonService::fail('type参数错误');
        }
        
        return JsonService::successful( MemberModel::List($this->request->uid,$params));
    }
    //获取用户自己的客户列表 
    public function getInMemberList()
    {
        $params = $this->request->param();
        if (empty($params['status'])) {
            return JsonService::fail('type参数错误');
        }
        $params['type'] = 1;
        return JsonService::successful( MemberModel::List($this->request->uid,$params));
    }
    function importExecl(string $file = '', int $sheet = 0, int $columnCnt = 0, &$options = [])
    {
        try {
            /* 转码 */
            $file = iconv("utf-8", "gb2312", $file);

            if (empty($file) OR !file_exists($file)) {
                throw new \Exception('文件不存在!');
            }

            /** @var Xlsx $objRead */
            $objRead = IOFactory::createReader('Xlsx');

            if (!$objRead->canRead($file)) {
                /** @var Xls $objRead */
                $objRead = IOFactory::createReader('Xls');

                if (!$objRead->canRead($file)) {
                    throw new \Exception('只支持导入Excel文件！');
                }
            }

            /* 如果不需要获取特殊操作，则只读内容，可以大幅度提升读取Excel效率 */
            empty($options) && $objRead->setReadDataOnly(true);
            /* 建立excel对象 */
            $obj = $objRead->load($file);
            /* 获取指定的sheet表 */
            $currSheet = $obj->getSheet($sheet);

            if (isset($options['mergeCells'])) {
                /* 读取合并行列 */
                $options['mergeCells'] = $currSheet->getMergeCells();
            }

            if (0 == $columnCnt) {
                /* 取得最大的列号 */
                $columnH = $currSheet->getHighestColumn();
                /* 兼容原逻辑，循环时使用的是小于等于 */
                $columnCnt = Coordinate::columnIndexFromString($columnH);
            }

            /* 获取总行数 */
            $rowCnt = $currSheet->getHighestRow();
            $data   = [];

            /* 读取内容 */
            for ($_row = 1; $_row <= $rowCnt; $_row++) {
                $isNull = true;

                for ($_column = 1; $_column <= $columnCnt; $_column++) {
                    $cellName = Coordinate::stringFromColumnIndex($_column);
                    $cellId   = $cellName . $_row;
                    $cell     = $currSheet->getCell($cellId);
                    $data[$_row][$cellName] = trim($currSheet->getCell($cellId)->getFormattedValue());
                    if (!empty($data[$_row][$cellName])) {
                        $isNull = false;
                    }
                }

                /* 判断是否整行数据为空，是的话删除该行数据 */
                if ($isNull) {
                    unset($data[$_row]);
                }
            }

            return $data;
        } catch (\Exception $e) {
            throw $e;
        }
    }

    //获取客户档案 
    public function getMemberDAinfo()
    {
        $params = $this->request->param();
        if (empty($params['customer_id'])) {
            return JsonService::fail('id参数错误');
        }
        $data = MemberModel::where('id', $params['customer_id'])->find()->toArray();
        $keys = array_keys($data);
        //处理图片
        foreach ($keys as $item) {
            if (stripos($item, 'image') !== false) {
                $data[$item] = image_domain($data[$item]);
            }
        }
        if($data['label']){
            $list = explode(',',$data['label']);
            $data['label_info'] =[];
            foreach($list as $value){
                $data['label_info'][$value] = DB::table('hs_member_label')->where('id', $value)->find();
            }
        }
//        $credit_report_file = explode(',',$data['credit_report_file']);
//        foreach ($credit_report_file as &$val){
//            $val = image_domain($val);
//        }
//        $data['credit_report_file'] = implode(',' ,$credit_report_file);
        return JsonService::successful($data);
    }
    //个人征信 
    public function getMemberZxinfo()
    {
        $params = $this->request->param();
        if (empty($params['customer_id'])) {
            return JsonService::fail('customer_id参数错误');
        }
        // $re = DB::table('hs_memaberpersonalcredit')->where('customer_id', $params['customer_id'])->find();
        return JsonService::successful(DB::table('hs_memaberpersonalcredit')->where('customer_id', $params['customer_id'])->find());
    }
    //跟进信息
    public function getMemberGjinfo()
    {
        $params = $this->request->param();
        if (empty($params['customer_id'])) {
            return JsonService::fail('id参数错误');
        }
        $data = DB::table('hs_memberfollowupinfo')
        ->alias('m')  // 
        ->join('user u', 'm.user_id = u.id')  // 关联user表
        ->where('m.customer_id', $params['customer_id'])
        // ->order('m.id desc')
        // ->select();
        ->field('m.*, u.nickname')  // 选择需要查询的字段
        ->order('m.id', 'desc')  // 按照id倒序排序
        // ->find();
        ->select();
        return JsonService::successful($data);
    }
    //通话信息
    public function getMemberThinfo()
    {
        $params = $this->request->param();
        if (empty($params['customer_id'])) {
            return JsonService::fail('id参数错误');
        }
        return JsonService::successful(DB::table('hs_membercallrecord')->where('customer_id', $params['customer_id'])->order('id', 'desc')->select());
    }

     //转换客户
    public function saveMemberAnduser(){
        $params = $this->request->param();
        if (!empty($params['id'])) {
            $re = MemberModel::where('id',$params['id'])
            ->update(['status'=>1]);
            if($re){
                return JsonService::successful('转换成功');
            }
        }
        return JsonService::fail('id参数错误');
    }
    //获取客户数量
    public function getInMemberAndUserCount(){
        $uid = $this->request->uid;
        return JsonService::successful([
            'yx'=>MemberModel::where('user_id',$uid)->where('status',1)->count(),
            'cj'=>MemberModel::where('user_id',$uid)->where('status',2)->count()
        ]);
    }
    
    //认领客户
    public function updateMemberAnduser(){
        $params = $this->request->param();
        if (!empty($params['id'])) {
            // $memberIds = explode(',', $params['id']);
            // if($memberIds ){
            //     foreach ($memberIds as $key => $value) {
            //        MemberModel::where('id',$value)->update(['user_id'=>$this->request->uid]);
            //     }
            // }
            // return JsonService::successful('转换成功');
            $re = MemberModel::where('id',$params['id'])->update(['user_id'=>$this->request->uid]);
            if($re){
                return JsonService::successful('认领成功');
            }
        }
        return JsonService::fail('id参数错误');
    }
    //修改信息
    public function upMemberZxDesc()
    {
        $data = $this->request->param();
        $params =$data;
        if (empty($params['id']) || empty($params['type'])) {
            return JsonService::fail('id-type参数错误');
        }
        unset($params['variationstatus']);
        if($params['type'] ==1 ){
            //客户档案信息
            $table ="hs_member";
            $params['updatetime'] = time();
            if($data['variationstatus']){
                if($params['upload_type']==1){
                    $params['ocr_pdf_file'] = $params['personal_credit_doc_file'];
                }
            }
        }
        if($params['type'] ==2 ){
            //个人征信信息
            $table ="hs_memaberpersonalcredit";
        }
        if($params['type'] ==3 ){
            //个人跟进信息
            $table ="hs_memberfollowupinfo";
        }
        if($params['type'] ==4 ){
            //个人通话信息
            $table ="hs_membercallrecord";
        }
        unset($params['type']);
        try{
            $result = Db::table($table)->where('id', $params['id'])->update($params);
            if($result){
                if($table='hs_member' && !empty($data['variationstatus'])){
                    //识别ocr
                    if($params['upload_type']==0){
                        $r = $this->ImgTCPDF($params);
                        if($r){
                            $params['ocr_pdf_file']=$r;
                        }
                    }
                    if(!empty($params['ocr_pdf_file'])){
                        self::uploadMemberZxDesc($params,$this->request->uid);
                    }
                }
                return JsonService::successful('修改成功');
            }
        }
        catch (\Exception $e) {
            return JsonService::fail($e->getMessage());
        }
        return JsonService::fail('修改失败');
    }

      

    //批量添加客户 
    public function fileAddMember(){
        $excelFile = $this->request->param('file');
        if(!$excelFile){
            return JsonService::fail('参数不对');
        }
        $file = explode('https://keguan.cc',$excelFile);
        $file = ROOT_PATH . DS . 'public' . DS . $file['1'];
        try {
            $data = $this->importExecl($file);
            unset( $data['1']);
            if(!$data){
                return JsonService::fail('内容为空');
            }
            $user = UserModel::info($this->request->uid);
            if(!$user['c_id']){
                return JsonService::fail('没有绑定公司！');
            }
            $indata =[];
            foreach ($data as $row) {
                $indata[] = [
                    'company_name' => $row['A'],
                    'legal_person_name' => $row['B'],
                    // 'shareholder_name' => $row['C'],
                    'phone1' => $row['C'],
                    'remark' => $row['D'],
                    // 'phone2' => $row['E'],
                    // 'phone3' => $row['F'],
                    'c_id' =>$user['c_id'],
                    'create_user_id'=> $this->request->uid,
                    'createtime' => time(),
                    'updatetime' =>time()
                ];
            }
            if(!$indata){
                return JsonService::fail('数据为空！');
            }
            if(Db::table('hs_member')->insertAll($indata)){
                return JsonService::successful('成功');
            }
        } catch (\PhpOffice\PhpSpreadsheet\Reader\Exception $e) {
            return JsonService::fail($e->getMessage());
        }
    }
    //添加客户信息
    public function addMemberZxDesc()
    {
        try{
            $params = $this->request->param();
            unset($params['variationstatus']);
            if (empty($params['type'])) {
                return JsonService::fail('type参数错误');
            }
            if($params['type'] ==1 ){
                //客户档案信息
                $table ="hs_member";
                $user = UserModel::info($this->request->uid);
                if(!$user['c_id']){
                    return JsonService::fail('没有绑定公司！');
                }
                $params['c_id'] = $user['c_id'];
                //生成pdf
                if($params['upload_type']==1){
                    $params['ocr_pdf_file'] = $params['personal_credit_doc_file'];
                }
                $params['create_user_id'] =$this->request->uid;
            }
            if($params['type'] ==2 ){
                //个人征信信息
                $table ="hs_memaberpersonalcredit";
            }
            if($params['type'] ==3 ){
                //个人跟进信息
                $table ="hs_memberfollowupinfo";
                $params['user_id']= $this->request->uid ;
            }
            if($params['type'] ==4 ){
                //个人通话信息
                $table ="hs_membercallrecord";
                $params['user_id']= $this->request->uid ;
            }
            $params['createtime'] = time();
            $params['updatetime'] = time();
            unset($params['type']);
            $result = Db::table($table)->insertGetId($params);
            if($result){
                if($table=='hs_member'){
                   //识别ocr
                    if($params['upload_type']==0){
                        $params['id']=$result;
                        $r = $this->ImgTCPDF($params);
                        if($r){
                            $params['ocr_pdf_file']=$r;
                        }
                    }
                    if($params['ocr_pdf_file']){
                        self::uploadMemberZxDesc($params,$this->request->uid);
                    }
                }else{
                    Db::table("hs_member")->where('id', $params['customer_id'])->update(['updatetime'=>time()]);
                }
                return JsonService::successful('成功');
            }
        }catch (\Exception $e) {
            return JsonService::fail($e->getMessage());
        }
        return JsonService::fail('错误');
    }


    public  function MemberOcr()
    {
        $params = $this->request->param();
        $result = Db::table('hs_member')->where('id',$params['id'])->find();
        //判断次数 
        if($result){
            $r= self::uploadMemberZxDesc($result,$result['user_id']);
            if($r){
                return JsonService::successful('操作成功!识别中，无需重复操作！');
            }
            return JsonService::fail('次数不足请充值！ocr服务请求失败！');
        }
        return JsonService::fail('找不到用户！');
    }

    public  function getMemberLabel()
    {
        return JsonService::successful( DB::table('hs_member_label')->order('id', 'desc')->select());
    }

    function ImgTCPDF($data){
        if(!empty($data['personal_credit_doc_file'])){
            //判断是否 图片
            //图片压缩pdf 
            // 图片文件列表
            // 图片文件路径
            $data['personal_credit_doc_file']=$data['personal_credit_doc_file'].',';
            $imageFiles = explode(',',$data['personal_credit_doc_file'])  ;
            // PDF 文件保存路径
            $pdfFile = ROOT_PATH . 'public/pdf/'.$data['legal_person_name'].$data['id'].'.pdf';
            // 创建 PDF 实例
            $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
            // 设置文档信息
            $pdf->SetCreator(PDF_CREATOR);
            $pdf->SetAuthor('Your Name');
            $pdf->SetTitle('Image to PDF');
            $pdf->SetSubject('Converting image to PDF');
            $pdf->SetKeywords('PDF, image, conversion, example');
            // 删除默认的页眉/页脚
            $pdf->setPrintHeader(false);
            $pdf->setPrintFooter(false);
            // 遍历每张图片并添加到 PDF 中
            foreach ($imageFiles as $imageFile) {
                if($imageFile){
                    // 添加一页
                    $pdf->AddPage();
                    // 插入图像到 PDF
                    $pdf->Image($imageFile, 10, 10, 180, 0, 'JPEG', '', '', true, 300, '', false, false, 0, false, false, false);
                }
            }
            // 插入图像到 PDF
            // $pdf->Image($imageFiles, 10, 10, 180, 0, 'JPEG', '', '', true, 300, '', false, false, 0, false, false, false);
            // 保存 PDF 文件到服务器
            $pdf->Output($pdfFile, 'F');
            // $path = '/pdf/'.$data['legal_person_name'].$data['id'].'.pdf';
            $path = 'https://keguan.cc/pdf/'.$data['legal_person_name'].$data['id'].'.pdf';
            $r = Db::table('hs_member')->where('id', $data['id'])->update(['ocr_pdf_file'=>$path]);
            if($r){
                return  $path;
            }
        }
        return false;
    }

    //文件扫描
    public static function uploadMemberZxDesc($data,$user_id=0)
    {
        $userinfo = UserModel::where('id', $user_id)->find();
        //判断是否 有次数 
        if (!empty($userinfo['ocrnum']) ) {
            $path = $data['ocr_pdf_file'];
            //修改路径 
            try{
                $re = self::postPdf($path,'http://120.77.217.104:5000/pdf');
                if($re){
                    $result = self::postPCurl(json_encode(['type' =>0,'path' =>$re['folder'],"url"=>"https://keguan.cc/api/Recruit/ocrnotify?id=".$data['id']]),'http://120.77.217.104:5000/ocr');
                    if($result['msg']=='success'){
                        //修改数据库
                        Db::table('hs_user_ocr_logs')->insert(['member_id'=>$user_id,'content'=>"扫码一次文件".$path,'createtime'=>date('Y-m-d H:i:s')]);
                        return  UserModel::where('id', $user_id)->setDec('ocrnum',1);
                    }
                }
            }catch (\Exception $e) {
                return false;
                // throw new \Exception($e->getMessage());
            }
        }
        return false;
    }
    

     public static function postPdf($data,$url){
        // 初始化 cURL
        $curl = curl_init();
        // 设置 cURL 选项
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        // // 设置连接超时时间，单位是秒
        // curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
        // // 设置请求超时时间，单位是秒
        // curl_setopt($curl, CURLOPT_TIMEOUT,60);
        $postData = array(
            'file' => new \CURLFile($data)
        );
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        // 执行 cURL 请求
        $response = curl_exec($curl);
        if ($response === false) {
            // 如果请求失败，输出错误信息
            echo 'cURL error: ' . curl_error($curl);
            // exit();
        }
        // 关闭 cURL 资源
        curl_close($curl);
        return json_decode($response, true) ;
    }

    public static function postPCurl($postData,$url){
        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>$postData,
        CURLOPT_HTTPHEADER => array(
            'User-Agent: Apifox/1.0.0 (https://apifox.com)',
            'Content-Type: application/json'
        ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return json_decode($response, true) ;
    }
    
    //获取ocr内容 
    public function getMemberOcr()
    {
        $params = $this->request->param();
        if (!empty($params['id'])) {
            $result = Db::table('hs_member_ocr')->where('member_id',$params['id'])->find();
            if($result){
                return JsonService::successful(json_decode($result['content'],true));
            }else{
                return JsonService::successful([]);
            }
        }
        return JsonService::fail('参数错误');
    }

    // 递归函数用于处理多层级数据
    // public  function renderData($data,$languagePack) {
    //     $html = "<table border='1'>";
    //     foreach ($data as $key => $value) {
    //         $translatedKey = isset($languagePack[$key]) ? $languagePack[$key] : $key;
    //         if (is_array($value)) {
    //             // 如果值是数组，则递归处理
    //             $html .= "<tr><td colspan='2'><strong>$translatedKey</strong></td></tr>";
    //             $html .=self::renderData($value, $languagePack);
    //         } else {
    //             // 否则直接输出键值对
    //             $html .= "<tr><td><strong>$translatedKey</strong></td><td>$value</td></tr>";
    //         }
    //     }
    //     $html .= "</table>";
    //     return $html;
        
    // }
    //获取表结构
    public function getTableFields()
    {

        // $result = Db::table('hs_member')->where('id',7)->find();
        // if($result){
        //     self::uploadMemberZxDesc($result);
        // }
        // exit();
        // $result = Db::table('hs_member_ocr')->where('member_id',2)->find();
        // if($result){
        //     $languagePack = json_decode(file_get_contents('zh.json'), true);
        //     // 将 JSON 数据解码为关联数组
        //     $data = json_decode($result['content'], true);
        //     // 在页面中输出数据
        //     echo "<h1>信用报告详情</h1>";
        //     echo  $this->renderData($data,$languagePack);
        //     exit();
        // }else{
        //     return JsonService::successful([]);
        // }
        $tableName ='hs_member_call_record'; // 获取请求中的表名参数
        $fields = Db::query("SHOW FULL COLUMNS FROM " . $tableName); // 获取表字段信息
        foreach ($fields as $item) {
            $nameArray[$item['Field']] =$item['Comment'];
        }
        return json($nameArray);
    }

}
